import { reqGetCode,reqUserRegister,reqUserLogin,reqUserInfo,reqLoginOut} from "@/api"
import { setToken,removeToken,getToken} from "@/utils/token"

const state={
  phoneCode:"",
  token:getToken(),
  userInfo:{}
}
const mutations={
 
  USERLOGIN(state,token){
    state.token=token
  },
  GETUSERINFO(state,data){
     state.userInfo=data
  },
  GETPHONE(state,phoneCode){
  state.phoneCode=phoneCode
  },
  CLEARClEAR(state){

    state.userInfo="";
    state.token=""; 
    removeToken()

  }
}
const actions={
   //获取验证码
 async getCode({commit},phone){
   let result= await reqGetCode(phone)

   if(result.code==200){
     commit("GETPHONE",result.data)
   }
  },
  //用户注册
    async userRegister({commit},user){
    let result=await reqUserRegister(user)
    console.log(result)
  },
  //用户登录
  async userLogin({ commit}, data) {
    let result = await reqUserLogin(data);
    console.log(result)
    
    //服务器下发token，用户唯一标识符(uuid)
    //将来经常通过带token找服务器要用户信息进行展示
    if (result.code == 200) {
      
      //用户已经登录成功且获取到tokenresult.nickName
      commit("USERLOGIN",result.data.token);
      //持久化存储token
      setToken(result.data.token);
      return "ok";
    } else {
      return Promise.reject(new Error(result.message+"或密码不正确"));
    }
  },
   //登录成功后保存信息
  async getUserInfo({commit}){
    let result=await reqUserInfo()
    console.log(result)
     if(result.code==200){
       commit("GETUSERINFO",result.data)
     }
  },
 
 async userLogout({commit}){
    
      let result=await reqLoginOut()
      console.log(result)
      if(result.code==200){
       commit("CLEARClEAR")
       return "ok"
      }else{
        return Promise.reject(new Error('faile'));
      }
  }
}
const getters={
}
export default{
  state,
  mutations,
  actions,
  getters
}